// ** React Imports
import { useContext } from 'react'
import { Link, useNavigate } from 'react-router-dom'

// ** Custom Hooks
import { useSkin } from '@hooks/useSkin'
import useJwt from '@src/auth/jwt/useJwt'

// ** Third Party Components
import toast from 'react-hot-toast'
import { useDispatch } from 'react-redux'
import { useForm, Controller } from 'react-hook-form'
import {
  Facebook,
  Twitter,
  Mail,
  GitHub,
  HelpCircle,
  Coffee,
  X,
} from 'react-feather'

// ** Actions
import { handleLogin } from '@store/authentication'

// ** Context
import { AbilityContext } from '@src/utility/context/Can'

// ** Custom Components
import Avatar from '@components/avatar'
import InputPasswordToggle from '@components/input-password-toggle'

// ** Utils
import { getHomeRouteForLoggedInUser } from '@utils'

// ** Reactstrap Imports
import {
  Row,
  Col,
  Form,
  Input,
  Label,
  Alert,
  Button,
  CardText,
  CardTitle,
  FormFeedback,
  UncontrolledTooltip,
} from 'reactstrap'

// ** Illustrations Imports
import illustrationsLight from '@src/assets/images/pages/login-v2.svg'
import illustrationsDark from '@src/assets/images/pages/login-v2-dark.svg'
import { loginEmailApi } from '../../../api/login'

// ** Styles
import '@styles/react/pages/page-authentication.scss'

const ToastContent = ({ t, name, role }) => {
  return (
    <div className="d-flex">
      <div className="me-1">
        <Avatar size="sm" color="success" icon={<Coffee size={12} />} />
      </div>
      <div className="d-flex flex-column">
        <div className="d-flex justify-content-between">
          <h6>{name}</h6>
          <X
            size={12}
            className="cursor-pointer"
            onClick={() => toast.dismiss(t.id)}
          />
        </div>
        <span>欢迎您！{name}</span>
      </div>
    </div>
  )
}
const defaultValues = {
  password: 'admin',
  loginEmail: 'admin@demo.com',
}
// const defaultValues = {
//   password: '12345678',
//   loginEmail: 'cs@ll.com',
// }

const Login = () => {
  // ** Hooks
  const { skin } = useSkin()
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const ability = useContext(AbilityContext)
  const {
    control,
    setError,
    handleSubmit,
    formState: { errors },
  } = useForm({ defaultValues })

  const source = skin === 'dark' ? illustrationsDark : illustrationsLight

  const onSubmit = (data) => {
    if (Object.values(data).every((field) => field.length > 0)) {
      const temp = {
        id: 1,
        fullName: '李',
        username: 'test',
        avatar: '/src/assets/images/portrait/small/avatar-s-11.jpg',
        email: 'admin@demo.com',
        role: 'admin',
        ability: [
          {
            action: 'manage',
            subject: 'all',
          },
        ],
        extras: {
          eCommerceCartItemsCount: 5,
        },
        accessToken:
          'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNjk3MTExNDgzLCJleHAiOjE2OTcxMTIwODN9.TQtxyPr8RzGN9GD-w6jwG93PGiE7dEywPRTRShfbqvA',
        refreshToken:
          'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNjk3MTExNDgzLCJleHAiOjE2OTcxMTIwODN9.3SqgLuRHuMMjYu1GftGl9tMZbjN8GNX8HMJK0kNiLxg',
      }
      dispatch(handleLogin(temp))
      ability.update([
        {
          action: 'manage',
          subject: 'all',
        },
      ])
      navigate(getHomeRouteForLoggedInUser('admin'))
      toast((t) => <ToastContent t={t} role={'admin'} name={'干部'} />)

      //   useJwt
      //     .login({ email: data.loginEmail, password: data.password })
      //     .then((res) => {
      //       const data = {
      //         ...res.data.userData,
      //         role: 'worker',
      //         accessToken: res.data.accessToken,
      //         refreshToken: res.data.refreshToken,
      //       }
      //       dispatch(handleLogin(data))
      //       ability.update([{ action: 'manage', subject: 'all' }])
      //       navigate(getHomeRouteForLoggedInUser('worker'))
      //       toast((t) => (
      //         <ToastContent
      //           t={t}
      //           role={'worker'}
      //           name={data.fullName || data.username || 'John Doe'}
      //         />
      //       ))
      //     })
      //     .catch((err) =>
      //       setError('loginEmail', {
      //         type: 'manual',
      //         message: err.response.data.error,
      //       })
      //     )
      // } else {
      //   for (const key in data) {
      //     if (data[key].length === 0) {
      //       setError(key, {
      //         type: 'manual',
      //       })
      //     }
      //   }
    }
  }

  return (
    <div className="auth-wrapper auth-cover">
      <Row className="auth-inner m-0">
        <Col className="d-none d-lg-flex align-items-center p-5" lg="8" sm="12">
          <div className="w-100 d-lg-flex align-items-center justify-content-center px-5">
            <img className="img-fluid" src={source} alt="Login Cover" />
          </div>
        </Col>
        <Col
          className="d-flex align-items-center auth-bg px-2 p-lg-5"
          lg="4"
          sm="12"
        >
          <Col className="px-xl-2 mx-auto" sm="8" md="6" lg="12">
            <CardTitle tag="h2" className="fw-bold mb-1">
              欢迎使用服务云平台! 👋
            </CardTitle>
            <CardText className="mb-2">使用邮箱登录</CardText>

            <Form
              className="auth-login-form mt-2"
              onSubmit={handleSubmit(onSubmit)}
            >
              <div className="mb-1">
                <Label className="form-label" for="login-email">
                  账号
                </Label>
                <Controller
                  id="loginEmail"
                  name="loginEmail"
                  control={control}
                  render={({ field }) => (
                    <Input
                      autoFocus
                      type="email"
                      placeholder="john@example.com"
                      invalid={errors.loginEmail && true}
                      {...field}
                    />
                  )}
                />
                {errors.loginEmail && (
                  <FormFeedback>{errors.loginEmail.message}</FormFeedback>
                )}
              </div>
              <div className="mb-1">
                <div className="d-flex justify-content-between">
                  <Label className="form-label" for="login-password">
                    密码
                  </Label>
                  <Link to="/forgot-password">
                    <small>忘记密码?</small>
                  </Link>
                </div>
                <Controller
                  id="password"
                  name="password"
                  control={control}
                  render={({ field }) => (
                    <InputPasswordToggle
                      className="input-group-merge"
                      invalid={errors.password && true}
                      {...field}
                    />
                  )}
                />
              </div>
              <div className="form-check mb-1">
                <Input type="checkbox" id="remember-me" />
                <Label className="form-check-label" for="remember-me">
                  记住
                </Label>
              </div>
              <Button type="submit" color="primary" block>
                登录
              </Button>
            </Form>
            <p className="text-center mt-2">
              <span className="me-25">没有账户?</span>
              <Link to="/register">
                <span>创建</span>
              </Link>
            </p>
          </Col>
        </Col>
      </Row>
    </div>
  )
}

export default Login
